package cn.alan.studynotes.utils;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * Created by chenbingwen on 2021/4/15.
 */
public class ValidationUtils {

    private static ValidatorFactory factory = Validation.byProvider(HibernateValidator.class)
            .configure()
            .failFast(true)
            .buildValidatorFactory();

    public static void v(Object o) {
        vThrowError(o, true);
    }

    public static <T> List<String> getErrors(T t) {
        return processValidate(t, true);
    }

    private static <T> List<String> processValidate(T t, Boolean showProperty) {
        if (t == null) {
            return Collections.emptyList();
        }
        Validator validator = factory.getValidator();

        Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);

        List<String> messageList = new ArrayList<>();

        for (ConstraintViolation<T> constraintViolation : constraintViolations) {
            if (BooleanUtils.isTrue(showProperty)) {
                messageList.add(constraintViolation.getMessage() + "，字段：" + constraintViolation.getPropertyPath());
            } else {
                messageList.add(constraintViolation.getMessage());
            }
        }
        return messageList;
    }

    private static void vThrowError(Object o, Boolean showProperty) {
        List<String> errorMsg = processValidate(o, showProperty);
        if (CollectionUtils.isNotEmpty(errorMsg)) {
            for (String msg : errorMsg) {
                throw new RuntimeException(msg);
            }
        }
    }

}
